<template>
  <van-tabs v-model:active="active" animated>
    <van-tab
      ><template #title>
        <van-icon name="comment-o" color="DeepSkyBlue" size="20px" />
        &nbsp;聊天信息
      </template>
      <ul v-if="active === 0" class="friend-items">
        <van-empty
          v-if="!ptsMsgList || ptsMsgList.length <= 0"
          description="暂无新的聊天信息"
        />
        <van-swipe-cell v-else v-for="ptsMsg in ptsMsgList"
          ><li @click="toChat(ptsMsg)" class="friend-item">
            <div class="avatar-container">
              <img :src="ptsMsg.fromUrl" class="avatar" />
            </div>
            <div class="friend-info">
              <div class="friend-apply">
                <span style="font-size: 16px">{{
                  ptsMsg.teamName ?? ptsMsg.fromName
                }}</span>
                <span style="font-size: 14px"
                  >{{ ptsMsg.text.substr(0, 12)
                  }}<span v-if="ptsMsg.text.length > 12">...</span></span
                >
              </div>
            </div>
            <div style="font-size: 14px">
              {{ moment(ptsMsg.createTime).format("MM-DD HH:mm") }}
            </div>
          </li>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              @click="
                chatListDel(
                  ptsMsg.scope,
                  ptsMsg.toId,
                  ptsMsg.fromId,
                  ptsMsg.teamId
                )
              "
              style="margin-top: 15px"
              class="delete-button"
            />
          </template>
        </van-swipe-cell></ul
    ></van-tab>
    <van-tab
      ><template #title>
        <van-icon name="bulb-o" color="DeepSkyBlue" size="24px" />
        &nbsp;好友申请
      </template>
      <ul v-if="active === 1" class="friend-items">
        <van-empty
          v-if="!friendMsgList || friendMsgList.length <= 0"
          description="暂无新的好友申请"
        />
        <li
          v-else
          v-for="friendMsg in friendMsgList"
          @click="friendDetail(friendMsg)"
          class="friend-item"
        >
          <div class="avatar-container">
            <img :src="friendMsg.friendUrl" class="avatar" />
          </div>
          <div class="friend-info">
            <div class="friend-apply">
              <p style="font-size: 16px">
                {{ friendMsg.friendName
                }}<span class="friend-name">(我是{{ friendMsg.note }})</span>
              </p>
            </div>
          </div>
          <div style="padding-right: 5px; width: 120px">
            <van-button
              style="width: 50px; height: 30px"
              size="small"
              v-if="friendMsg.status === 0"
              plain
              type="danger"
              @click.stop="toHandle(2, friendMsg)"
              >拒绝
            </van-button>
            <van-button
              style="width: 50px; height: 30px; float: right"
              size="small"
              v-if="friendMsg.status === 0"
              plain
              type="success"
              @click.stop="toHandle(1, friendMsg)"
              >同意
            </van-button>
            <p
              class="apply"
              v-if="friendMsg.status === 1"
              style="font-size: 14px; color: green; width: 90px"
            >
              <van-icon name="certificate" size="16px" />
              已接受
            </p>
            <p
              v-if="friendMsg.status === 2"
              style="font-size: 14px; color: red; width: 90px"
            >
              <van-icon name="revoke" size="16px" />
              已拒绝
            </p>
          </div>
        </li>
      </ul></van-tab
    >
    <van-tab
      ><template #title>
        <van-icon name="service-o" color="DeepSkyBlue" size="18px" />
        &nbsp;系统信息
      </template>
      <ul v-if="active === 2" class="friend-items">
        <van-empty
          v-if="!sysMsgList || sysMsgList.length <= 0"
          description="暂无新的系统信息"
        />
        <van-swipe-cell v-else v-for="sysMsg in sysMsgList">
          <li
            @click="
              showSystem(
                sysMsg.toId,
                sysMsg.teamId,
                sysMsg.text,
                sysMsg.sysStatus
              )
            "
            class="friend-item"
          >
            <div class="avatar-container">
              <img :src="sysMsg.fromUrl" class="avatar" />
            </div>
            <div class="friend-info">
              <div class="friend-apply">
                <span style="font-size: 16px">{{ sysMsg.fromName }}</span>
                <span style="font-size: 14px"
                  >{{ sysMsg.text.substr(0, 12)
                  }}<span v-if="sysMsg.text.length > 12">...</span></span
                >
              </div>
            </div>
            <div style="font-size: 14px">
              {{ moment(Number(sysMsg.createTime)).format("MM-DD HH:mm") }}
            </div>
          </li>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              @click="
                chatListDel(
                  sysMsg.scope,
                  sysMsg.toId,
                  sysMsg.fromId,
                  sysMsg.teamId
                )
              "
              style="margin-top: 15px"
              class="delete-button"
            />
          </template>
        </van-swipe-cell></ul
    ></van-tab>
  </van-tabs>
  <van-popup
    v-model:show="showCenter"
    round
    style="height: 60%"
    :style="{ padding: '20px' }"
  >
    <span v-if="sysMessage" v-html="sysMessage"></span>
    <van-steps
      v-else
      v-for="sysMessage in sysMsgForTeam"
      direction="vertical"
      active="1"
    >
      <van-step
        :class="
          sysMessage.type == 0
            ? 'teamCreate'
            : sysMessage.type == 1
            ? 'teamDisband'
            : sysMessage.type == 2
            ? 'teamJoin'
            : sysMessage.type == 3
            ? 'teamQuit'
            : 'teamExpire'
        "
      >
        <h3>{{ sysMessage.text }}</h3>
        <p>{{ moment(Number(sysMessage.createTime)).format("MM-DD HH:mm") }}</p>
      </van-step>
    </van-steps>
  </van-popup>
</template>

<script setup lang="ts">
import moment from "moment";
import { showConfirmDialog } from "vant";
import { inject, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ChatType } from "../models/chat";
import { FriendsType } from "../models/friends";
import { UserType } from "../models/user";
import myAxios from "../plugins/myAxios";
import { getCurrentUser } from "../services/user";

const active = ref(0); //当前标签页
watch(active, () => {
  if (active.value === 0) {
    ptsMsgList.value = [];
    getMsgList(1);
  } else if (active.value === 1) {
    getFriendMsg();
  } else if (active.value === 2) {
    ptsMsgList.value = [];
    getMsgList(3);
  }
});

/**
 * 获取消息列表
 * @param type
 */
const currentUser = ref({} as UserType); //当前用户
const ptsMsgList = ref([] as ChatType[]); //私聊和队伍消息列表
const sysMsgList = ref([] as ChatType[]); //系统消息列表
let sysStstusMap = new Map(); //队伍信息和id的映射
const getMsgList = async (scope: number) => {
  const res = await myAxios.get("/chat/chatList", {
    params: {
      userId: currentUser.value.id,
      scope,
    },
  });
  if (res.code === 0 && res.data) {
    if (scope === 3) {
      sysMsgList.value = [];
      sysStstusMap = new Map();
      let flag = true;
      res.data.forEach((r) => {
        const teamId = r.teamId;
        if (teamId) {
          flag = false;
          const arr = sysStstusMap.get(teamId);
          if (arr) arr.push(r);
          else sysStstusMap.set(r.teamId, [r]);
        } else {
          sysMsgList.value.push(r);
        }
      });
      for (const key of sysStstusMap.keys()) {
        const arr = sysStstusMap.get(key).sort((a: ChatType, b: ChatType) => {
          return a.createTime - b.createTime;
        });
        sysMsgList.value.push(arr[arr.length - 1]);
      }
    } else {
      ptsMsgList.value = res.data;
    }
  }
};

/**
 * 获取好友请求
 */
const friendMsgList = ref([] as FriendsType[]); //好友申请列表
const getFriendMsg = async () => {
  const res = await myAxios.get("/friends/msgList", {
    params: {
      userId: currentUser.value.id,
    },
  });
  if (res.code === 0 && res.data) {
    friendMsgList.value = res.data;
  }
};

/**
 * 处理好友申请
 */
const reload = inject("reload"); //刷新函数
const toHandle = async (status: number, friendMsg: FriendsType) => {
  if (status === 2) {
    showConfirmDialog({
      message: "确认拒绝吗",
    })
      .then(async () => {
        handle(status, friendMsg);
      })
      .catch(() => {});
  } else {
    handle(status, friendMsg);
  }
};
const handle = async (status: number, friendMsg: FriendsType) => {
  const res = await myAxios.post("/friends/handle", {
    userId: friendMsg.userId,
    userUrl: currentUser.value.avatarUrl,
    userName: friendMsg.userName,
    friendId: friendMsg.friendId,
    friendUrl: friendMsg.friendUrl,
    note: friendMsg.note,
    status: status,
  });
  if (res.code === 0) {
    reload();
  }
};

/**
 * 访问好友主页
 */
const router = useRouter();
const friendDetail = (friend: {}) => {
  router.push({
    path: "/user",
    query: {
      friendInfo: JSON.stringify(friend),
    },
  });
};

/**
 * 进入聊天列表
 * @param ptsMsg
 */
const friendly = ref(false);
const toChat = async (ptsMsg: ChatType) => {
  if (ptsMsg.scope === 1) {
    const res = await myAxios.get("/friends/isFriend", {
      params: {
        userId: ptsMsg.toId,
        friendId: ptsMsg.fromId,
      },
    });
    friendly.value = res.code === 0 && res.data;
  }
  router.push({
    path: "/chat",
    query: {
      friendId: ptsMsg.fromId,
      friendInfo: JSON.stringify(ptsMsg),
      scope: ptsMsg.scope,
      teamId: ptsMsg.teamId,
      teamName: ptsMsg.teamName,
      friendly: friendly.value,
    },
  });
};

/**
 * 展示系统信息列表记录并删除对应的redis记录
 */
const showCenter = ref(false); //展示系统消息的弹出层
const sysMessage = ref(""); //系统消息内容
const sysMsgForTeam = ref([] as ChatType[]); //队伍有关的系统消息内容
const isNotRead = ref(1); //是否未读，是的话点击查看会删除消息提醒
const showSystem = async (
  toId: number,
  teamId: number,
  text: string,
  sysStatus: string
) => {
  let sysStatusArr: any[] = [];
  if (teamId) {
    sysMsgForTeam.value = sysStstusMap.get(teamId);
    sysStstusMap.get(teamId).forEach((sys) => {
      sysStatusArr.push(sys.sysStatus);
    });
  } else {
    sysMessage.value = text;
    sysStatusArr.push(sysStatus);
  }

  showCenter.value = true;
  if (isNotRead.value === 1) {
    myAxios
      .post("/chat/statusDel", {
        toId,
        sysStatus: sysStatusArr,
      })
      .then((res) => {
        if (res.code === 0) {
          isNotRead.value = res.data;
        }
      });
  }
};

/**
 * 删除对应的消息列表
 */
const chatListDel = async (
  scope: number,
  toId: number,
  fromId: number,
  teamId: number
) => {
  let res = null;
  if (scope === 1) {
    res = myAxios.post("/chat/chatListDel", {
      scope,
      toId,
      fromId,
    });
  } else if (scope === 2) {
    res = myAxios.post("/chat/chatListDel", {
      scope,
      toId: currentUser.value.id,
      teamId,
    });
  } else {
    const sysStatusArr: any[] = [];
    sysStstusMap.get(teamId).forEach((sys) => {
      sysStatusArr.push(sys.sysStatus);
    });
    res = myAxios.post("/chat/chatListDel", {
      scope,
      toId,
      sysStatus: sysStatusArr,
    });
  }
  res.then((r) => {
    if (r.code === 0) {
      reload();
    }
  });
};

const route = useRoute();
onMounted(async () => {
  currentUser.value = await getCurrentUser("1");
  const activeLast = Number(route.query.active);
  active.value = activeLast ?? 0;
  if (active.value === 0) getMsgList(1);
});
</script>

<style scoped>
@import "../assets/css/message.css";
</style>
